<template>
  <div class="mod-prod-info">
    <el-form ref="dataFormRef" :model="dataForm" label-width="100px">
      <el-form-item label="产品图片">
        <!-- <mul-pic-upload v-model="dataForm.imgs" /> -->
        <div>
          <el-upload action="#" :auto-upload="false" list-type="picture-card" :on-progress="handlePictureCardPreview"
            :on-change="handleUploadSuccess">
            <el-icon v-if="!modelValue">
              <Plus />
            </el-icon>
            <img v-if="modelValue" style="width: 136px;height: 134px;float: right;" alt="" :src="dataForm.pic"
              class="pic">

          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </div>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">
            上架
          </el-radio>
          <el-radio :label="0">
            下架
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="产品分类" :rules="[{ required: true, message: '请选择产品分类' }]" prop="categoryId">
        <el-col :span="8">
          <el-cascader v-model="category.selected" expand-trigger="hover" :options="category.list"
            :props="category.props" change-on-select @change="handleCategoryChange" />
        </el-col>
      </el-form-item>
      <el-form-item label="产品分组" :rules="[{ required: true, message: '请选择产品分组' }]">
        <el-col :span="8">
          <el-select v-model="dataForm.tagList" multiple style="width: 250px" placeholder="请选择">
            <el-option v-for="item in tags" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="产品名称" prop="prodName" :rules="[
        { required: true, message: '产品名称不能为空' },
        { pattern: /\s\S+|S+\s|\S/, message: '请输入正确的产品名称', trigger: 'blur' }
      ]">
        <el-col :span="8">
          <el-input v-model="dataForm.prodName" placeholder="产品名称" maxlength="50" />
        </el-col>
      </el-form-item>
      <el-form-item label="产品卖点" prop="brief" :rules="[
        { required: false, pattern: /\s\S+|S+\s|\S/, message: '请输入正确的产品卖点', trigger: 'blur' }
      ]">
        <el-col :span="8">
          <el-input v-model="dataForm.brief" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="产品卖点" />
        </el-col>
      </el-form-item>
      <el-form-item label="配送方式">
        <el-checkbox v-model="dataForm.deliveryMode.hasShopDelivery">
          商家配送
        </el-checkbox>
        <el-checkbox v-model="dataForm.deliveryMode.hasUserPickUp">
          用户自提
        </el-checkbox>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone" :rules="[
        { required: true, message: '手机号不能为空' },
        { pattern: /^(\+?[1-9]\d{0,2}[- ]?)?[1-9]\d{6,14}$/, message: '请输入正确的产品名称', trigger: 'blur' }
      ]">
        <el-col :span="8">
          <el-input v-model="dataForm.phone" placeholder="请输入联系方式" maxlength="50" />
        </el-col>
      </el-form-item>
      <prod-transport v-show="dataForm.deliveryMode.hasShopDelivery" v-model="dataForm.deliveryTemplateId" />
      <sku-tag ref="skuTagRef" :sku-list="dataForm.skuLists" @change="skuTagChangeSkuHandler" />
      <sku-table ref="skuTableRef" v-model="dataForm.skuLists" :prod-name="dataForm.prodName" />
      <el-form-item label="产品详情" prop="content">
        <!-- <tiny-mce ref="contentRef" v-model="dataForm.content" style="width:1000px" /> -->
        <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode"
          style="border-bottom: 1px solid #ccc" />
        <Editor :defaultConfig="editorConfig" :mode="mode" v-model="dataForm.content"
          style="width:1000px;height: 400px; overflow-y: hidden" @onCreated="handleCreated" @onChange="handleChange"
          @onDestroyed="handleDestroyed" @onFocus="handleFocus" @onBlur="handleBlur" @customAlert="customAlert"
          @customPaste="customPaste" />

      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit()">
          确定
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { treeDataTranslate, idList } from '@/utils'
import ProdTransport from './components/prod-transport.vue'
import SkuTag from './components/sku-tag.vue'
import SkuTable from './components/sku-table.vue'
import { Debounce } from '@/utils/debounce'
import $cookie from 'vue-cookies'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import axios from 'axios';


const modelValue = ref(false)

// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef();

// 编辑器回调函数
const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  // console.log('created', editorRef.value);

};
const handleChange = (editor) => {
  console.log('change:', editor.getHtml());
};
const handleDestroyed = (editor) => {
  console.log('destroyed', editor);
};
const handleFocus = (editor) => {
  console.log('focus', editor);
};
const handleBlur = (editor) => {
  console.log('blur', editor);
};
const customAlert = (info, type) => {
  alert(`【自定义提示】${type} - ${info}`);
};
const customPaste = (editor, event, callback) => {
  console.log('ClipboardEvent 粘贴事件对象', event);

  // 自定义插入内容
  editor.insertText('xxx');

  // 返回值（注意，vue 事件的返回值，不能用 return）
  callback(false); // 返回 false ，阻止默认粘贴行为
  // callback(true) // 返回 true ，继续默认的粘贴行为
};

const editorConfig = {
  MENU_CONF: {
    uploadImage: {
      customUpload: (file) => {
        return new Promise((resolve, reject) => {
          const formData = new FormData();
          formData.append('file', file);
          axios({
            url: uploadAction,
            method: 'post',
            headers: {
              ...uploadHeaders,
              'Content-Type': 'multipart/form-data'
            },
            data: formData
          })
            .then((res) => {
              const imgUrl = res.data.data.url;
              const editor = editorRef.value;
              if (!editor) {
                ElMessage({
                  message: '编辑器实例未正确获取，无法插入图片',
                  type: 'error',
                  duration: 1500
                });
                reject(new Error('编辑器实例未正确获取'));
                return;
              }
              const urlPattern = /^https?:\/\/[^\s/$.?#].[^\s]*$/i;
              if (!urlPattern.test(imgUrl)) {
                ElMessage({
                  message: '图片 URL 格式不正确，无法插入图片',
                  type: 'error',
                  duration: 1500
                });
                reject(new Error('图片 URL 格式不正确'));
                return;
              }
              editor.insertText(imgUrl);
              resolve(imgUrl);
            })
            .catch((err) => {
              ElMessage({
                message: '图片上传失败，请检查网络或联系管理员',
                type: 'error',
                duration: 1500
              });
              reject(err);
            });
        });
      }
    }
  }
};

const emit = defineEmits(['refreshDataList'])
const uploadHeaders = { Authorization: $cookie.get('Authorization'), username: '000' }
const uploadAction = http.adornUrl('/file/upload')
// 分类树展示与回显
const category = reactive({
  list: [],
  selected: [],
  props: {
    value: 'categoryId',
    label: 'categoryName'
  }
})
// 规格列表
const dataForm = ref({
  prodName: '',
  brief: '',
  pic: '',
  imgs: '',
  categoryId: 0,
  prodId: 0,
  skuLists: [],
  tagList: [],
  content: '',
  status: 1,
  deliveryMode: {
    hasShopDelivery: false,
    hasUserPickUp: false
  },
  deliveryTemplateId: null
})
const tags = ref([])
onMounted(() => {
  dataForm.value.prodId = useRoute().query.prodId
  getDataList()
})

const skuTableRef = ref(null)
const skuTagRef = ref(null)
/**
 * 获取分类数据
 */
const getDataList = () => {
  getTagList()
  getCategoryList().then(() => {
    if (dataForm.value.prodId) {
      // 获取产品数据
      http({
        url: http.adornUrl(`/prod/prod/info/${dataForm.value.prodId}`),
        method: 'get',
        params: http.adornParams()
      })
        .then(({ data }) => {
          // console.log(JSON.parse(data.deliveryMode));

          dataForm.value = data
          dataForm.value.deliveryMode = JSON.parse(data.deliveryMode)
          skuTagRef.value?.init(data.skuLists)
          skuTableRef.value?.init()
          category.selected = idList(category.list, dataForm.value.categoryId, 'categoryId', 'children').reverse()
          dataForm.value.tagList = data.tagList
          dataForm.value.phone = data.phone
          dataForm.value.pic = data.pic
          modelValue.value = true
        })
    } else {
      nextTick(() => {
        dataFormRef.value?.resetFields()
        skuTagRef.value?.init()
        dataForm.value.pic = ''
        dataForm.value.imgs = ''
      })
    }
  })
}
/**
 * 获取分类信息
 */
const getCategoryList = () => {
  return http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams()
  })
    .then(({ data }) => {
      category.list = treeDataTranslate(data, 'categoryId', 'parentId')
    })
}
/**
 * 选择分类改变事件
 * @param val
 */
const handleCategoryChange = (val) => {
  dataForm.value.categoryId = val[val.length - 1]
}

const router = useRouter()
const dataFormRef = ref(null)
/**
 * 表单提交
 */
const onSubmit = Debounce(() => {
  dataFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    // if (!dataForm.value.imgs) {
    //   errorMsg('请选择图片上传')
    //   return
    // }
    if (!dataForm.value.deliveryMode) {
      errorMsg('请选择配送方式')
      return
    }
    if (dataForm.value.deliveryMode.hasShopDelivery && !dataForm.value.deliveryTemplateId) {
      errorMsg('请选择运费模板')
      return
    }
    if (dataForm.value.deliveryTemplateId == null) {
      dataForm.value.deliveryTemplateId = ''
    }
    const param = Object.assign({}, dataForm.value)
    // 设置价格和库存
    paramSetPriceAndStocks(param)

    if (!dataForm.value.prodId) {
      dataForm.value.prodId = ''
    }
    if (!dataForm.value.price) {
      dataForm.value.price = ''
    }
    if (!dataForm.value.soldNum) {
      dataForm.value.soldNum = ''
    }
    if (!dataForm.value.version) {
      dataForm.value.version = ''
    }
    if (!dataForm.value.shopName) {
      dataForm.value.shopName = ''
    }
    if (dataForm.value.skuList) {
      delete dataForm.value.skuList
    }
    const formData = new FormData();
    // 添加非文件类型数据
    for (const key in dataForm.value) {
      if (key === 'deliveryMode' || key === 'skuLists') {
        // formData.append('deliveryMode', JSON.stringify(dataForm.value[deliveryMode]));
        // formData.append('skuLists', JSON.stringify(dataForm.value[skuLists]));
        formData.append(key, JSON.stringify(dataForm.value[key]));
      } else if (key !== 'imgs') {
        formData.append(key, dataForm.value[key]);
      }
    }
    // 添加文件类型数据（假设dataForm.value.imgs是文件对象，这里可根据实际情况调整）
    if (dataForm.value.imgs) {
      formData.append('files', dataForm.value.imgs);
    } else {
      formData.append('files', '');
    }
    if (dataForm.value.prodId) {
      if (dataForm.value.imgs) {
        formData.append('oldPic', dataForm.value.pic);

      } else {
        formData.append('oldPic', '');

      }
    }
    http({
      url: http.adornUrl(dataForm.value.prodId ? '/prod/prod/update' : '/prod/prod/save'),
      method: dataForm.value.prodId ? 'put' : 'post',
      headers: {
        'content-type': 'multipart/form-data;'
      },
      // responseType: 'blob',
      data: formData,

    })
      .then(() => {
        ElMessage({
          message: '操作成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            router.push({
              path: '/prod/prodList'
            })
            emit('refreshDataList')
          }
        })
      })
  })
})

const paramSetPriceAndStocks = (param) => {
  // 商品库存
  param.totalStocks = 0
  // 商品价格
  param.price = 0
  // 商品原价
  param.oriPrice = 0
  // 商品实际库存
  for (let i = 0; i < param.skuLists.length; i++) {
    const element = param.skuLists[i]
    if (element.status !== 1) {
      continue
    }
    if (param.price === 0) {
      param.price = element.price ? Number.parseFloat(element.price) : 0
    }
    // 商品价格为最低价的那件商品的价格
    param.price = Math.min(param.price, element.price)
    if (param.price === element.price) {
      param.oriPrice = element.oriPrice ? Number.parseFloat(element.oriPrice) : 0
    }
    param.totalStocks += element.stocks ? Number.parseInt(element.stocks) : 0
  }
  // 如果sku没有商品名称，则使用商品的商品名称
  if (param.skuLists.length === 1) {
    param.skuLists[0].prodName = dataForm.value.prodName
  }
}
const skuTagChangeSkuHandler = (skuLists) => {
  const prodName = dataForm.value.prodName
  skuLists.forEach(sku => {
    if (sku.properties) {
      sku.skuName = ''
      const properties = sku.properties.split(';')
      for (const propertiesKey in properties) {
        sku.skuName += properties[propertiesKey].split(':')[1] + ' '
      }
      sku.prodName = prodName + ' ' + sku.skuName
    }
  })
  dataForm.value.skuLists = skuLists
}
const errorMsg = (message) => {
  ElMessage({
    message,
    type: 'error',
    duration: 1500
  })
}

/**
 * 获取所有的分组信息
 */
const getTagList = () => {
  http({
    url: http.adornUrl('/prod/prodTag/listTagList'),
    method: 'get',
    params: http.adornParams()
  })
    .then(({ data }) => {
      tags.value = data
    })
}


const handlePictureCardPreview = (file) => {
  console.log(file, "00000000000");

  dataForm.value.imgs = file.raw
}
const handleUploadSuccess = (response, file, fileList) => {
  console.log(file, "00000000000");
  dataForm.value.imgs = file[0].raw
}

</script>
